<?php
/* SVN FILE: $Id: app_controller.php 25 2008-08-29 21:58:28Z namaless $ */
/**
 * Funzioni base.
 *
 * @author			Pereira Pulido Nuno Ricardo | Namaless | namaless@gmail.com
 * @copyright		Copyright 1981-2008, Namaless.
 * @link			http://www.namaless.com Namaless Blog
 * @version			1.0
 * @version			$Revision: 25 $
 * @modifiedby		$LastChangedBy: namaless $
 * @lastmodified	$Date: 2008-08-29 23:58:28 +0200 (ven, 29 ago 2008) $
 * @license			http://www.opensource.org/licenses/gpl-license.php GNU Public License
 */

/**
 * Prints out debug information about given variable.
 *
 * Only runs if debug level is non-zero.
 *
 * @param boolean $var Variable to show debug information for.
 * @param boolean $showHtml If set to TRUE, the method prints the debug data in a screen-friendly way.
 * @param boolean $showFrom If set to TRUE, the method prints from where the function was called.
 */
function debug($var = FALSE)
{
	$calledFrom = debug_backtrace();
	print "<strong>".str_replace(base_path(), "", $calledFrom[0]['file'])."</strong> (line <strong>".$calledFrom[0]['line']."</strong>)";
	print "\n<pre class=\"debug\">\n";
	$var = print_r($var, TRUE);
	print "{$var}\n</pre>\n";
	print '<div style="clear:both;"></div>';
}

/**
 * Gets an environment variable from available sources, and provides emulation
 * for unsupported or inconsisten environment variables (i.e. DOCUMENT_ROOT on
 * IIS, or SCRIPT_NAME in CGI mode).  Also exposes some additional custom
 * environment information.
 *
 * @param  string $key Environment variable name.
 * @return string Environment variable setting.
 */
function env($key)
{
	if ( $key == 'HTTPS' )
	{
		if ( isset($_SERVER) AND ! empty($_SERVER) )
		{
			return ( isset($_SERVER['HTTPS']) AND $_SERVER['HTTPS'] == 'on' );
		}
		else
		{
			return ( strpos(env('SCRIPT_URI'), 'https://') === 0 );
		}
	}

	if ( $key == 'SCRIPT_NAME' )
	{
		if ( env('CGI_MODE') AND isset($_ENV['SCRIPT_URL']) )
		{
			$key = 'SCRIPT_URL';
		}
	}

	$val = NULL;
	if ( isset($_SERVER[$key]) )
	{
		$val = $_SERVER[$key];
	}
	else if ( isset($_ENV[$key]) )
	{
		$val = $_ENV[$key];
	}
	else if ( getenv($key) !== FALSE )
	{
		$val = getenv($key);
	}

	if ( $key == 'REMOTE_ADDR' AND $val == env('SERVER_ADDR') )
	{
		$addr = env('HTTP_PC_REMOTE_ADDR');
		if ( $addr != NULL )
		{
			$val = $addr;
		}
	}

	if ( $val !== NULL )
	{
		return $val;
	}

	switch ( $key )
	{
		case 'SCRIPT_FILENAME':
			if ( defined('SERVER_IIS') AND SERVER_IIS === TRUE )
			{
				return str_replace('\\\\', '\\', env('PATH_TRANSLATED'));
			}
		break;

		case 'DOCUMENT_ROOT':
			$offset = 0;
			if ( ! strpos(env('SCRIPT_NAME'), '.php') )
			{
				$offset = 4;
			}

			return substr(env('SCRIPT_FILENAME'), 0, strlen(env('SCRIPT_FILENAME')) - (strlen(env('SCRIPT_NAME')) + $offset));
		break;

		case 'PHP_SELF':
			return str_replace(env('DOCUMENT_ROOT'), '', env('SCRIPT_FILENAME'));
		break;

		case 'CGI_MODE':
			return (substr(php_sapi_name(), 0, 3) == 'cgi');
		break;

		case 'HTTP_BASE':
			return preg_replace('/^([^.])*/i', NULL, env('HTTP_HOST'));
		break;
	}

	return NULL;
}


/**
 * Implementazione dell'autoload delle classi.
 *
 * @param	string		Nome della classe da caricare.
 */
function __autoload($class_name)
{
	// Genero la path dinamica in base all'array definito poco sopra.
	$complete_path = core_path('classes/' . strtolower($class_name) . '.php');

	// Cerco nella directory del core.
	include_once ( $complete_path );
}

/**
 * Parse out the attributes
 *
 * Some of the functions use this
 *
 * @access	private
 * @param	array
 * @param	bool
 * @return	string
 */
function parse_attributes($attributes, $javascript = FALSE)
{
	if ( is_string($attributes) )
	{
		return ($attributes != '') ? ' ' . $attributes : '';
	}

	$att = '';
	foreach ( $attributes AS $key => $val )
	{
		if ( $javascript == TRUE )
		{
			$att .= $key . '=' . $val . ',';
		}
		else
		{
			$att .= ' ' . $key . '="' . $val . '"';
		}
	}

	if ( $javascript == TRUE AND $att != '' )
	{
		$att = substr($att, 0, -1);
	}

	return $att;
}

/**
 * Restituisce l'url corretto.
 *
 * @return string
 **/
function base_url()
{
	$base_url = ( (isset($_SERVER['HTTPS']) AND $_SERVER['HTTPS'] == "on" ) ? "https" : "http");
	$base_url .= "://" . $_SERVER['HTTP_HOST'];
	if ( ! isset($_SERVER['ORIG_SCRIPT_NAME']) )
	{
		$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']);
	}
	else
	{
		$base_url .= str_replace(basename($_SERVER['ORIG_SCRIPT_NAME']), "", $_SERVER['ORIG_SCRIPT_NAME']);
	}
	
	return $base_url;
}


/**
 * Abbreviazione per la cattura della linea della lingua.
 *
 * @param string Linea della lingua da catturare.
 * @return string
 */
function __($line)
{
	$args = func_get_args();
	return Lang::line($line, $args);
}


/**
 * Implementazione del trigger_error().
 */
function show_error_404($heading, $file)
{
	$heading = str_replace(base_path(), "", $heading);
	$file = str_replace(base_path(), "", $file);

	// Se impostato in fase di sviluppo viene mostrato l'errore generale con maggiori dettagli.
	if ( App::setting('Enviroments.development') )
	{
		show_error($heading);
	}
	
	$template = core_path("errors/error_404.php");

	if ( file_exists($template) )
	{
		include_once ( $template );
		exit;
	}

	die($message);
}

function show_error($heading)
{
	$template = core_path("errors/error_general.php");
	$message = debug_backtrace();

	if ( file_exists($template) )
	{
		include_once ( $template );
		
		// Se in fase di produzione blocca lo script.
		if ( ! App::setting('Enviroments.development') )
		{
			exit;
		}
	}
	else
	{
		die($heading);
	}
}

/**
 * Restituisce la path completa.
 *
 * @param string Path oltre la base_path.
 * @return string
 */
function base_path($path = "")
{
	return __BASE_PATH__ . $path;
}


/**
 * Restituisce la path dalla cartella di micro-php.
 *
 * @param string Path.
 * @return string
 */
function core_path($path = "")
{
	return __CORE_PATH__ . $path;
}


/**
 * Restituisce le impostazioni.
 *
 * @param string ID da passare ad App::setting().
 * @return string
 */
function setting($setting)
{
	return App::setting($setting);
}


/**
 * Restituisce le impostazioni Enveroments.
 *
 * @param string
 * @return string
 * @author Namaless
 **/
function env_setting($setting = "")
{
	if ( ! $setting )
	{
		return App::setting("Enviroments");
	}
	
	return App::setting("Enviroments.{$setting}");
}